package com.zhixue.media.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhixue.media.mapper.*;
import com.zhixue.media.po.*;
import com.zhixue.media.service.MediaProcessService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Auther: 李 力
 * @Date: 2025/4/28
 * @Description: com.zhixue.media.service.impl
 * @version: 1.0
 */
@Service
public class MediaProcessServiceImpl extends ServiceImpl<MediaProcessMapper, MediaProcess> implements MediaProcessService {

    @Autowired
    private MediaProcessMapper mediaProcessMapper;

    @Autowired
    private MediaFilesMapper mediaFilesMapper;

    @Autowired
    private MediaProcessHistoryMapper historyMapper;

    @Override
    public List<MediaProcess> getMediaProcessList(int shardIndex, int shardTotal, int count) {
        return mediaProcessMapper.selectListByShardIndex(shardTotal, shardIndex, 3, count);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int startTask(long id) {
        return mediaProcessMapper.startTask(id, 3);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveProcessFinishStatus(Long taskId, String status, String fileId, String url, String errorMsg) {
        MediaProcess mediaProcess = getById(taskId);
        if (mediaProcess == null) {
            return;
        }
        //如果任务执行失败
        ///更新mediaprocess表的状态
        if ("3".equals(status)) {
            mediaProcess.setStatus("3");
            mediaProcess.setFailCount(mediaProcess.getFailCount() + 1);
            mediaProcess.setErrormsg(errorMsg);
            mediaProcessMapper.updateById(mediaProcess);
            return;
        }
        //如果任务执行成功
        ///更新mediafile表中的url
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileId);
        mediaFiles.setUrl(url);
        mediaFilesMapper.updateById(mediaFiles);

        ///更新mediaprocess表的状态
        mediaProcess.setStatus("2");
        mediaProcess.setFinishDate(new Date());
        mediaProcess.setUrl(url);
        mediaProcessMapper.updateById(mediaProcess);

        ///将mediaprocess表记录插入到history表中
        MediaProcessHistory mediaProcessHistory = new MediaProcessHistory();
        BeanUtils.copyProperties(mediaProcess, mediaProcessHistory);
        historyMapper.insert(mediaProcessHistory);

        //从medisprocess删除当前任务
        mediaProcessMapper.deleteById(taskId);
    }
}
